package com.parsechina.hpush.broker.config;

import com.parsechina.hpush.broker.internal.MqttProtocolProcessor;
import com.parsechina.hpush.broker.spi.IPersistentStore;
import com.parsechina.hpush.broker.spi.ProtocolProcessor;
import com.parsechina.hpush.broker.spi.persistence.h2.H2PersistentStore;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @author linfeng
 * @date 2019-07-23
 **/
@Configuration
public class PushServerConfiguration {

    @Bean
    public EventLoopGroup bossGroup() {
        return new NioEventLoopGroup();
    }

    @Bean
    public EventLoopGroup workerGroup() {
        return new NioEventLoopGroup();
    }

    @Primary
    @Bean(value = "persistentStore", destroyMethod = "close")
    public IPersistentStore h2PersistentStore(HPushConfig config) {
        return new H2PersistentStore(config);
    }

//    @Bean(value = "persistentStore", destroyMethod = "close")
//    public IPersistentStore mapDBPersistentStore(HPushConfig config,
//                                                 RedissonClient redissonClient) {
//        return new RedisPersistentStore(config, redissonClient);
//    }

    @Bean
    public ProtocolProcessor protocolProcessor(RedissonClient redissonClient, HPushConfig config, IPersistentStore persistentStore) {


        boolean allowAnonymous = config.getAllowAnonymous();
        boolean allowAnonymousClient = config.getAllowAnonymousClient();
        boolean allowZeroByteClientId = config.getAllowZeroByteClientId();

        String instanceId = null;
        if (config.getCluster() != null) {
            instanceId = config.getCluster().getInstanceId();
        }
        if (StringUtils.isEmpty(instanceId)) {
            instanceId = UUID.randomUUID().toString();
        }

        return new MqttProtocolProcessor(persistentStore.subscriptionsStore(), persistentStore.messagesStore(),
                persistentStore.sessionsStore(), persistentStore.authenticatorStore(), persistentStore.clientStore(),
                allowAnonymous, allowAnonymousClient, allowZeroByteClientId, instanceId, redissonClient);

    }

}
